﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraBars;
using ProjectHost;
using TM.Common;
using TM.Data;
using TM.Data.ViewModels;
using TM.Data.ViewModels.VmMapper;
using TM.Plugable;

namespace TaskManagement
{
    public partial class MainScreen : Form
    {
        private Dictionary<Guid, Form> ProjectScreenList;
        List<BarButtonItem> buttonItems = new List<BarButtonItem>();
        Session projectSession = new Session();
        private Guid? currentProjectId;
        private bool isCancelClosing = false;

        private const string additionalValueKey = "mnuProject";

        public MainScreen()
        {
            InitializeComponent();
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            ProjectScreenList = new Dictionary<Guid, Form>();
            
            var vmMapper = VmMapperFactories.GetMapper<IVmMapper>();
            var ioCParam = new IoCParams();

            projectSession = vmMapper.ExtractFromDbo(true);

            if (projectSession != null)
            {
                foreach (var prj in projectSession.Projects)
                {
                    var editor = new AppointmentEditorScreen()
                                     {
                                         Text = prj.Name,
                                         WindowState = FormWindowState.Maximized
                                     };

                    editor.SetIoC(ioCParam, vmMapper);
                    editor.MdiParent = this;
                    editor.Closing += new CancelEventHandler(frm_Closing);
                    editor.ProjectDataIsChanged+=new ProjectDataIsChangedHandler(editor_ProjectDataIsChanged);
                    ProjectScreenList.Add(prj.ID, editor);
                }
            }

            //ProjectScreenList.Add(1, new ProjectEditorScreen() { Text = "Avelo document", WindowState = FormWindowState.Maximized });
            //ProjectScreenList.Add(2, new ProjectEditorScreen() { Text = "Technical training", WindowState = FormWindowState.Maximized });
            //ProjectScreenList.Add(3, new Form1() { Text = "Grantt view", WindowState = FormWindowState.Maximized });

            InitializeMenuProjects();
            EnableDisableButtons(false, true);

        }

        private void editor_ProjectDataIsChanged(object sender, bool isdirty)
        {
            EnableDisableButtons(isdirty);
        }

        private void EnableDisableButtons(bool isDirty, bool isInitializing = false)
        {
            btnSave.Enabled = isDirty;

            if(isInitializing)
            {
                btnAddnewTask.Enabled = false;
                btnDeleteCurrentTask.Enabled = false;
                btnDeleteCurrentProject.Enabled = false;
            }

            if(currentProjectId.HasValue)
            {
                btnDeleteCurrentProject.Enabled = true;
                btnAddnewTask.Enabled = true;
            }
        }

        protected override void OnClosing(CancelEventArgs e)
        {
            if (isCancelClosing)
            {
                e.Cancel = true;
                return;
            }

            isCancelClosing = false;
            base.OnClosing(e);
        }
        
        private void InitializeMenuProjects()
        {
            var links = drProjects.LinksPersistInfo.Cast<DevExpress.XtraBars.LinkPersistInfo>();
            var removeItems = links.Where(item => item.Item.Name.StartsWith("mnuProject")).ToList();
            for (int i = removeItems.Count() - 1; i >= 0; i--)
            {
                drProjects.LinksPersistInfo.Remove(removeItems[i]);
            }

            var rbitems = ribbonControl1.Items.Cast<DevExpress.XtraBars.BarItem>();
            var removeRbItems = rbitems.Where(item => item.Name.StartsWith("mnuProject")).ToList();
            for (int i = removeRbItems.Count() - 1; i >= 0; i--)
            {
                ribbonControl1.Items.Remove(removeRbItems[i]);
            }

            int m = 1;
            foreach (var kv in ProjectScreenList)
            {
                DevExpress.XtraBars.BarButtonItem mnuProject = new BarButtonItem();

                mnuProject.Caption = kv.Value.Text;
                mnuProject.Id = m;
                mnuProject.ImageIndex = 10;// 9;
                mnuProject.Name = "mnuProject" + (kv.Key);
                mnuProject.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.mnuProject_ItemClick);
                buttonItems.Add(mnuProject);
                m++;
            }
            ribbonControl1.AddBarButtonItemsIntoBarsubitem(drProjects, buttonItems.ToArray());


        }

        private void mnuProject_ItemClick(object sender, ItemClickEventArgs e)
        {
            currentProjectId = new Guid(e.Item.Name.Replace(additionalValueKey, ""));
            var frm = GetProjectScreen(currentProjectId.Value);

            frm.Show();
            frm.Activate();
            frm.WindowState = FormWindowState.Maximized;

            var iForm = (IProjectEditor) frm;
            if (!iForm.IsDataLoaded)
            {
                iForm.LoadProjectInformation(currentProjectId.Value);
            }
            
            foreach (var buttonItem in buttonItems)
            {
                buttonItem.ImageIndex = 10;
            }
            
            e.Item.ImageIndex = 9;

            EnableDisableButtons(isDirty: false);
        }

        void frm_Closing(object sender, CancelEventArgs e)
        {
            
            var iForm = (IProjectEditor)sender;
            var session = iForm.Session;
            var form = (Form)sender;

            if (iForm.IsDirty)
            {
                var msgResult = MessageBox.Show(
                        "Dự án '" + form.Text + "' đã thay đổi thông tin.\r\nBạn có muốn ghi lại những thay đổi của dự án trước khi thoát?",
                        "Saving...", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question,
                        MessageBoxDefaultButton.Button3);
                if (msgResult == DialogResult.Cancel)
                {
                    e.Cancel = true;
                    isCancelClosing = true;
                    return;
                }
                else if (msgResult == DialogResult.No)
                {
                    ProjectScreenList.Remove(iForm.ProjectId);
                    isCancelClosing = false;
                }
                else
                {
                    iForm.Save();
                    ProjectScreenList.Remove(iForm.ProjectId);
                    isCancelClosing = false;
                }
            }
            
        }

        private void btnSave_ItemClick(object sender, ItemClickEventArgs e)
        {
            var frm = GetProjectScreen(currentProjectId.Value);
            var iForm = (IProjectEditor)frm;

            iForm.Save();

        }

        private Form GetProjectScreen(Guid screenId)
        {
            return ProjectScreenList[screenId];
        }

        private void btnAddnewTask_ItemClick(object sender, ItemClickEventArgs e)
        {
            var frm = GetProjectScreen(currentProjectId.Value);
            var iForm = (IProjectEditor)frm;
            iForm.CreateNewTask();
        }
    }
}
